//
//  PersonalCenterViewController.m
//  Comma
//
//  Created by dlios on 15-1-13.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "PersonalCenterViewController.h"
#import "PersonalCenterView.h"
#import "EditDetailViewController.h"
#import "MyDynamicViewController.h"
#import "AFNetWorkingYU.h"
#import "GlobalMethod.h"
#import "URLMacro.h"
#import "UpLoadMyPhoto.h"
#import "YRSideViewController.h"
#import "VPImageCropperViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "LoadIndicator.h"
#import "Reachability.h"

#define ORIGINAL_MAX_WIDTH 640.0f

@interface PersonalCenterViewController ()<EditDetailViewControllerDelegate, VPImageCropperDelegate>

@end

@implementation PersonalCenterViewController

- (void)loadView
{
    self.personalCenter = [[PersonalCenterView alloc] initWithLeftButton:@"" RightButton:@"编辑" Title:@"个人中心" FooterView:FooterViewStateNone];
    self.view = self.personalCenter;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createMyCenter];
    [self getDataFromServer];
    self.load = [[LoadIndicator alloc] init];
    self.dic = [NSDictionary dictionary];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    YRSideViewController * sideview = [YRSideViewController share];
    sideview.needSwipeShowMenu= YES;
    
}
- (void)createMyCenter
{
    self.rightButton = self.personalCenter.rightButton;
    self.leftButton = self.personalCenter.leftButton;
    //编辑点击事件（注意 ：  点击编辑的点击事件 需要判断是否是用户本身访问，可能用用户的id把。。。如果是非用户 去掉编辑 重新生成一个页面 没有我的动态仅仅有用户的基本信息即可。或者将编辑编程详细。。并且撤销详情页面的所有点击事件）
    [self.rightButton addTarget:self action:@selector(rightButtonAction:) forControlEvents:UIControlEventTouchUpInside];


    [self.leftButton addTarget:self action:@selector(leftButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    //类别点击事件
    //已经没有用了
//// 给我新创建的视图 传值  是一个字典  从上一页传过来的数据
//    self.personalCenter.InforDic = [NSDictionary dictionaryWithDictionary:self.myDic];

}

#pragma mark - 从服务器获取数据(给所有控件初始值)
- (void)getDataFromServer
{
    NSString *key = [GlobalMethod getApproveKey];
    NSString *device = [GlobalMethod GetIOSUUID];
    
    NSString *str =[NSString stringWithFormat:@"approveKey=%@&deviceParam=%@", device, key];
    NSString *getUrl = [NSString stringWithFormat:@"%@?%@", URL_USER_GETDETAIL, str];
    
    Reachability * reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
    if ([reach currentReachabilityStatus] != NotReachable) {
    [AFNetWorkingYU netWorkingHanderGetGataWithUrl:getUrl resultBlock:^(id result) {
        if ([result isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dic = (NSDictionary *)result;
        NSString *str = [result objectForKey:@"msg"];
        str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"%@", str);
            [LoadIndicator stopAnimationInView:self.view];
        if ([[dic objectForKey:@"msg"] isEqualToString:@"success"])
        {
            NSDictionary *my = [dic objectForKey:@"obj"];
            for (NSString *key in my.allKeys) {
                if ([[my objectForKey:key] isKindOfClass:[NSNull class]]) {
                    [my setValue:@"" forKey:key];
                }
            }
          
            self.personalCenter.InforDic = [NSDictionary dictionaryWithDictionary:my];
            
            [self.leftButton addTarget:self action:@selector(leftButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            //我的动态点击事件（背景条）
            [self.personalCenter.myDynamic addTarget:self action:@selector(myDynamicButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            //我的动态点击事件（button）
            [self.personalCenter.button addTarget:self action:@selector(myDynamicButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            //照片点击事件(添加了手势)
            UITapGestureRecognizer *portraitTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(photoButtonAction)];
            [self.personalCenter.myPhoto addGestureRecognizer:portraitTap];
            
            //点击照片后 灰色背景的点击事件
            [self.personalCenter.backView addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            //点击相机的点击事件
            [self.personalCenter.fromCamera addTarget:self action:@selector(pickImageFromCamera) forControlEvents:UIControlEventTouchUpInside];
            //点击相册的点击事件
            [self.personalCenter.fromAlbum addTarget:self action:@selector(pickImageFromAlbum) forControlEvents:UIControlEventTouchUpInside];
            
            //得到未读消息
            [self getUnreadMessageNumber];
           
        }
        } else {
            UIView *fondView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
            [fondView setBackgroundColor:[UIColor whiteColor]];
            [self.view addSubview:fondView];
            [LoadIndicator networkStateNotReachableInView:fondView];
        }
    }];
    }
    else
    {
        UIView *fondView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
        [fondView setBackgroundColor:[UIColor whiteColor]];
        [self.view addSubview:fondView];
        [LoadIndicator networkStateNotReachableInView:fondView];
    }
    
}

//类别
- (void)leftButtonAction:(id)sender
{
    YRSideViewController * sideview = [YRSideViewController share];
    sideview.needSwipeShowMenu= YES;
    if (sideview.rootViewController.view.frame.origin.x == 0) {
        [sideview showLeftViewController:YES];
        [sideview.rootViewController.view setFrame:CGRectMake(SCREEN_WIDTH / 3 * 2, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    }
    else
    {
        [sideview.rootViewController.view setFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    }
}

//编辑
- (void)rightButtonAction:(id)sender
{
    NSLog(@"you did it!!!");
    EditDetailViewController *edit = [[EditDetailViewController alloc] init];
    edit.delegate = self;
    [self.navigationController pushViewController:edit animated:YES];
}

//我的动态
- (void)myDynamicButtonAction:(id)sender
{
    NSLog(@"ssssss");
    MyDynamicViewController *dynamic = [[MyDynamicViewController alloc] init];
    [self.navigationController pushViewController:dynamic animated:YES];
    //点击的时候  关闭定时器（注意 这里有个问题  就是要实时刷新数据，当一有数据更新动态的时候  就要启动定时器，还有动态消息数量 也要实时刷新 在文顶顶的博客里有）
   
}

#pragma mark - 获取用户未读消息总数
- (void)getUnreadMessageNumber
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *signalTimer = [user objectForKey:@"timer"];
    
    NSString *key = [GlobalMethod getApproveKey];
    NSString *device = [GlobalMethod GetIOSUUID];
    
    NSString *str =[NSString stringWithFormat:@"approveKey=%@&deviceParam=%@", device, key];
    NSString *getUrl = [NSString stringWithFormat:@"%@?%@", URL_GET_UNREAD_MSG, str];
    
    Reachability * reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
    if ([reach currentReachabilityStatus] != NotReachable) {
  
    [AFNetWorkingYU netWorkingHanderGetGataWithUrl:getUrl resultBlock:^(id result) {
        if ([result isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dic = (NSDictionary *)result;
        NSString *str = [dic objectForKey:@"msg"];
        str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        if ([[dic objectForKey:@"obj"] isKindOfClass:[NSNull class]]) {
            [dic setValue:@"" forKey:@"obj"];
        }
        if ([[dic objectForKey:@"msg"] isEqualToString:@"操作完成"]) {
            
            NSString *obj = [NSString stringWithFormat:@"%@", [dic objectForKey:@"obj"]];
            NSLog(@"%@", obj);
            //获取消息是否有未读(如果有未读  打开计时器， 没有 就关闭)
            if ([obj isEqualToString:@""] || [obj isEqualToString:@"0"] || obj == nil) {
                if (self.personalCenter.timer && [signalTimer isEqualToString:@"1"]) {
                    [self.personalCenter removeTimer];
                    [user setObject:@"0" forKey:@"timer"];
                }
            }
            else
            {
                if ([signalTimer isEqualToString:@"0"]) {
                    [self.personalCenter addTimer];
                    [user setObject:@"1" forKey:@"timer"];
                }
            }
        }
        }
        else
        {
            UIView *fondView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
            [fondView setBackgroundColor:[UIColor whiteColor]];
            [self.view addSubview:fondView];
            [LoadIndicator networkStateNotReachableInView:fondView];
        }
        
    }];
    }
    else
    {
        UIView *fondView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
        [fondView setBackgroundColor:[UIColor whiteColor]];
        [self.view addSubview:fondView];
        [LoadIndicator networkStateNotReachableInView:fondView];

    }
    
}

//照片选择器弹出
- (void)photoButtonAction
{
    [self.personalCenter.backView setFrame:CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_HEIGHT - 20)];
    [UIView animateWithDuration:0.2 animations:^{
        [self.personalCenter.chooseView setFrame:CGRectMake(0, SCREEN_HEIGHT - 88, SCREEN_WIDTH, 88)];
    }];
  
}
//照片选择器收回
- (void)backButtonAction:(id)sender
{
    [self.personalCenter.backView setFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - 108)];
    [UIView animateWithDuration:0.2 animations:^{
        [self.personalCenter.chooseView setFrame:CGRectMake(0, SCREEN_HEIGHT + 88, SCREEN_WIDTH, 88)];
    }];
}
#pragma mark - 选择相册
- (void)pickImageFromAlbum
{
    
    // 从相册中选取
    
    if ([self isPhotoLibraryAvailable]) {
        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        controller.navigationBar.barTintColor = [UIColor blackColor];

        controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
        [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
        controller.mediaTypes = mediaTypes;
        controller.delegate = self;
        [self presentViewController:controller
                           animated:YES
                         completion:^(void){
                             NSLog(@"Picker View Controller is presented");
                         }];

        
    }

}

#pragma mark - 选择相机
- (void)pickImageFromCamera
{
   
    
    // 拍照
    if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        controller.sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([self isFrontCameraAvailable]) {
            controller.cameraDevice = UIImagePickerControllerCameraDeviceFront;
        }
        NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
        [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
        controller.mediaTypes = mediaTypes;
        controller.delegate = self;
        [self presentViewController:controller
                           animated:YES
                         completion:^(void){
                             NSLog(@"Picker View Controller is presented");
                         }];

        
    }
    
    


}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        portraitImg = [self imageByScalingToMaxSize:portraitImg];
        // 裁剪
        VPImageCropperViewController *imgEditorVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, 100.0f, self.view.frame.size.width, self.view.frame.size.width) limitScaleRatio:3.0];
        imgEditorVC.delegate = self;
        [self presentViewController:imgEditorVC animated:YES completion:^{
            
            self.dic = [NSDictionary dictionaryWithDictionary:info];
            
        }];
        
    
    }];
}
//上传头像
- (void)transferMyDataToServer:(NSString *)myPhoto
{
    NSString *myPicture = [myPhoto substringFromIndex:16];
    NSLog(@"%@",myPicture);
    NSString *key = [GlobalMethod getApproveKey];
    NSString *device = [GlobalMethod GetIOSUUID];
    NSString *str =[NSString stringWithFormat:@"approveKey=%@&deviceParam=%@&", device, key];
    NSString *getUrl = [NSString stringWithFormat:@"%@?%@img=%@", URL_USER_INFO_EDIT, str,myPicture];
   
    Reachability * reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
    if ([reach currentReachabilityStatus] != NotReachable) {

    [AFNetWorkingYU netWorkingHanderGetGataWithUrl:getUrl resultBlock:^(id result) {
        if ([result isKindOfClass:[NSDictionary class]]) {
            NSString *str = [result objectForKey:@"msg"];
            str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSLog(@"%@", str);
            [self.load stopAnimationLoadView];
            self.view.userInteractionEnabled = YES;
            //此时应该插入一个动画 “正在同步服务器，请稍后” ,返回结果显示是否修改成功
            if ([str isEqualToString:@"编辑成功！"]) {
                [self.load stopAnimationLoadView];
            
                [self showTheResult:@"头像编辑成功！" msg:nil];
            }
            else
            {
                [self showTheResult:@"头像编辑失败" msg:@"未登录,或登录已过期"];
            }
        }
        else {
            UIView *fondView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
            [fondView setBackgroundColor:[UIColor whiteColor]];
            [self.view addSubview:fondView];
            [self.load stopAnimationLoadView];
            [LoadIndicator networkStateNotReachableInView:fondView];

        }
        
    }];
    }
    else
    {
        [self.load stopAnimationLoadView];
        UIView *fondView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
        [fondView setBackgroundColor:[UIColor whiteColor]];
        [self.view addSubview:fondView];
        [LoadIndicator networkStateNotReachableInView:fondView];
    }

    
}
#pragma mark - 显示信息保存的状态 是否保存成功
- (void)showTheResult:(NSString *)title msg:(NSString *)msg
{
    if (IOS_VERSION >= 8.0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alert animated:YES completion:nil];
        [self performSelector:@selector(dismissMyAlert) withObject:alert afterDelay:2];
    }
    else
    {
        UIAlertView * alert= [[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [alert show];
        [self performSelector:@selector(dismissAlert:) withObject:alert afterDelay:1.2];
    }
    
}
- (void)dismissMyAlert
{
    [self dismissViewControllerAnimated:YES completion:nil];
    
}
- (void)dismissAlert:(UIAlertView *)alert
{
    if(alert){
        [alert dismissWithClickedButtonIndex:[alert cancelButtonIndex] animated:YES];
        
    }
    
    
}
//完成剪切图片 上传服务器（代理方法）
#pragma mark VPImageCropperDelegate
- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    //剪切图片后放到头像上
    self.personalCenter.myPhoto.image = editedImage;
    
    [self.personalCenter.backView setFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - 44)];
    
    [self.personalCenter.chooseView setFrame:CGRectMake(0, SCREEN_HEIGHT + 88, SCREEN_WIDTH, 88)];
    
    //设置状态栏高亮
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    
    //点击确定后让剪辑器消失
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
        
        
        //添加上传 加载动画
        [self.load addLoadView:self.personalCenter];
     
        self.view.userInteractionEnabled = NO;
        
        
        
        //上传图片
        NSString *type = [self.dic objectForKey:UIImagePickerControllerMediaType];
        
        //当选择的类型是图片
        if ([type isEqualToString:@"public.image"])
        {
            
            @autoreleasepool {
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    NSData *data;
                    
                    UIImage * oImage = [self fixOrientation:editedImage];
                    data = UIImageJPEGRepresentation(oImage, 0.005);
                    
                    UIImage * newImage = [UIImage imageWithData:data];
                    data = UIImagePNGRepresentation(newImage);
                    
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [UpLoadMyPhoto uploadWithImageName:@"iPhoneImage" imageData:data finish:^(NSData *resultData) {
                                if ([resultData isKindOfClass:[NSData class]]) {
                                    
                           
                                NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:resultData options:NSJSONReadingMutableContainers error:nil];
                                NSLog(@"%@",dic);
                                NSArray *array = [dic objectForKey:@"avatarUrls"];
                                NSString *myPic = [array firstObject];
                                //                                   /user/mobi_edit
                                [self transferMyDataToServer:myPic];
                                NSLog(@"上传图片 = %@",[dic objectForKey:@"msg"]);
                                   
                                }
                                else
                                {
                                    [self.load stopAnimationLoadView];
                                    UIView *fondView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
                                    [self.view addSubview:fondView];
                                    [LoadIndicator networkStateNotReachableInView:fondView];

                                }
                            }];
                        });
                    
                });
            }
            
        }
    }];
}
//点击取消按钮，取消剪辑图片（代理方法）
- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    //点击取消后让剪辑器消失

    [self.personalCenter.backView setFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - 44)];
    
    [self.personalCenter.chooseView setFrame:CGRectMake(0, SCREEN_HEIGHT + 88, SCREEN_WIDTH, 88)];
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
 
    }];
}




- (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
       
        [self.personalCenter.backView setFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - 44)];
      
        [self.personalCenter.chooseView setFrame:CGRectMake(0, SCREEN_HEIGHT + 88, SCREEN_WIDTH, 88)];

    }];
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    
}
//uiimagepickerController的代理方法
#pragma mark camera utility
//是否允许访问相册
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}

#pragma mark image scale utility 图片的缩放功能
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}
//头像图片高清

#pragma mark - controller设置一个属性在这里接受协议传的值 然后在这里刷新数据  就不用再刷新页面了
- (void)transferInformation:(NSDictionary *)myInformation
{
    NSLog(@"%@",myInformation);
    self.myDic = [NSDictionary dictionaryWithDictionary:myInformation];
    [self.personalCenter.profile setText:[self.myDic objectForKey:@"profile"]];
    [self.personalCenter.school setText:[self.myDic objectForKey:@"school"]];
    [self.personalCenter.grade setText:[self.myDic objectForKey:@"grade"]];
    [self.personalCenter.ageAndSex setText:[self getMyAgeAndSex]];
    [self.personalCenter.major setText:[self.myDic objectForKey:@"major"]];
    [self.personalCenter.dept setText:[self.myDic objectForKey:@"dept"]];
    [self.personalCenter.myName setText:[self.myDic objectForKey:@"nick"]];
    
    
}

- (NSString *)getMyAgeAndSex
{
    
    NSString *age = [self.myDic objectForKey:@"birth"];
    age = [self getMyAge:age];
    NSString *gender = [self.myDic objectForKey:@"gender"];
    
    if (([age isEqualToString:@""] || age == nil) && (![gender isEqualToString:@""] || gender != nil)) {
        NSString *ageAndGender = [NSString stringWithFormat:@"    %@", gender];
        return ageAndGender;
    }
    else if ( ([gender isEqualToString:@""] || gender == nil) && (![age isEqualToString:@""] || age != nil)) {
        NSString *ageAndGender = [NSString stringWithFormat:@"%@   ", age];
        return ageAndGender;
    }
    else if ( ([age isEqualToString:@""] || age == nil) && ([gender isEqualToString:@""] || gender == nil))
    {
        
        return nil;
    }
    else
    {
        NSString *ageAndGender = [NSString stringWithFormat:@"%@ %@", age, gender];
        return ageAndGender;
    }
}

#pragma mark - 根据生日 获取年龄
- (NSString *)getMyAge:(NSString *)birthday
{
    
    NSString *timeStr = birthday;
    //得到数组的年月日
    NSArray *myBirth = [birthday componentsSeparatedByString:@"-"];
    NSLog(@"%@", myBirth);
    
    
    
    
    NSDateFormatter *date=[[NSDateFormatter alloc] init];
    [date setDateFormat:@"YY-MM-dd"];
    NSDate *d=[date dateFromString:timeStr];
    
    NSTimeInterval late=[d timeIntervalSince1970]*1;
    
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval now=[dat timeIntervalSince1970]*1;
    NSString *timeString=@"";
    
    NSTimeInterval cha=now-late;
    
    if (cha/86400>1)
    {
#pragma mark - fuck!! 次数不需要计算了   因为是从自己生日那天算起的 除以365的时候余数是从生日开始的
        /*
                NSInteger day =  cha / 86400;
                NSInteger year = day / 365;
                NSInteger myDays = [self calculateYear:[[myBirth firstObject] integerValue] MonthDays:[[myBirth objectAtIndex:1] integerValue] days:[[myBirth lastObject] integerValue]];
                if ((day % 365) > myDays) {
                    year ++;
                }
         */
        
        timeString = [NSString stringWithFormat:@"%f", cha/86400/365 + 1];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"%@", timeString];
    }
    
    return timeString;
}





#pragma mark - 每次页面出现的时候都会先刷新数据
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.personalCenter.dynamiChange) {
         [self getUnreadMessageNumber];
    }
    //如果视图已经存在  那么就不需要在此进行加载了
    if (!self.personalCenter) {
        [LoadIndicator addIndicatorInView:self.view];

    }
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];

    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
